package com.team10.hotel.controller;

import com.team10.hotel.domain.Permission;
import com.team10.hotel.domain.Role;
import com.team10.hotel.service.PermissionService;
import com.team10.hotel.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/getAll")
    public String getAllRoleAndPermissionName(Model model){
        List<Role> roleList=roleService.findAll();
        for (Role role:roleList
             ) {
            List<Permission> permissions=permissionService.findByRoleId(role.getRoleId());
            role.getPermissions().addAll(permissions);
        }
        model.addAttribute("roleList",roleList);
        return "roleList";
    }

    @RequestMapping("/add")
    public String addRole(Model model){
        List<Permission> permissionList=permissionService.findAll();
        model.addAttribute("role",new Role());
        model.addAttribute("permissionList",permissionList);
        return "roleAdd";
    }

    @RequestMapping("/edit")
    public String editInfoPrint(String id,Model model){
        Role role=roleService.findByPrimaryKey(Integer.parseInt(id));
        List<Permission> permissions=permissionService.findByRoleId(Integer.parseInt(id));
        role.getPermissions().addAll(permissions);
        List<Permission> permissionList=permissionService.findAll();
        model.addAttribute("role",role);
        model.addAttribute("permissionList",permissionList);
        return "roleAdd";
    }

    @RequestMapping("/save")
    public String saveRole(Role role,String permissionIds){
        roleService.saveOrUpdate(role,permissionIds);
        return "redirect:/role/getAll";
    }

    @RequestMapping("/delete")
    public String deleteRole(String id){
        int del=roleService.deleteRole(Integer.parseInt(id));
        if(del==1) return "redirect:/role/getAll";
        else return "404";
    }

}
